package myJs.common

import myJs.api.Api
import myJs.cps.Style
import myJs.myPkg.reactBootstrap.Modal
import myJs.myPkg.reactHookForm._
import myJs.myPkg.{SwalOptions, layer, swal}
import myJs.tool.Tool
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.SampleId.Add2Db
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.web.html._

import scala.concurrent.{Future, Promise}
import scala.scalajs.js
import scala.scalajs.js.timers.SetTimeoutHandle
import scala.scalajs.js.{JSON, |}

/**
 * Created by yz on 21/1/2022
 */
@react object AddCp {

  case class Props(refreshTableB: () => Future[Unit], show: Boolean = false, showChange: Boolean => Unit)

  val component = FunctionalComponent[Props] { props =>

    val useForm = ReactHookForm.useForm(UseFormOptions(mode = "onChange"))
    val (sampleId, setSampleId) = useState("")
    val (delayTimer, setDelayTimer) = useState(null: SetTimeoutHandle)

    object FTool {

      def handleClose = () => {
        props.showChange(false)
      }

      def sampleIdChange = (v: String) => {
        setSampleId(v)
      }

      def sampleIdValidateF = (v: String) => {
        import shared.pojo.Pojo.sampleId._
        val request = SampleIdCheck.Request(sampleId = v)
        val promise = Promise[Boolean | String]()

        def f = Api.sampleId.sampleIdCheck(request).map { response =>
          val info = "样本编号"
          val rs = if (response.valid) {
            true
          } else {
            s"${info}已存在！"
          }
          rs.asInstanceOf[Boolean | String]
        }

        js.timers.clearTimeout(delayTimer)
        val curDelayTimer = js.timers.setTimeout(300) {
          f.map { rs =>
            promise.success(rs)
          }
        }
        setDelayTimer(curDelayTimer)
        promise.future
      }

      def add = () => {
        val index = layer.alert(Tool.myElement, Tool.layerOptions)
        val request = Add2Db.Request(ids = List(sampleId), account = Tool.getAccount)
        Api.sampleId.add2Db(request).map { xhr =>
          props.refreshTableB().map { x =>
            layer.close(index)
            swal(SwalOptions(title = "成功", text = "新增成功!", `type` = "success"))
            props.showChange(false)
          }
        }
        ()
      }

    }

    useEffect(() => {
      if (props.show) {
        useForm.trigger("sampleId")
      }
    }, List(props.show)
    )

    Modal(onHide = FTool.handleClose, show = props.show, size = "addModal")(
      Modal.Header(bsPrefix = "modal-header bg-primary", closeButton = true)(
        Modal.Title(
          i(className := "fa fa-plus"),
          span(style := Style(fontWeight = "bold"), id := "lblAddTitle", " 新增样本编号")
        )
      ),
      form(id := "form", data - "toggle" := "validator", className := "form-horizontal",
        onSubmit := {
          useForm.handleSubmit((data: js.Dictionary[js.Any]) => {
            println(JSON.stringify(data))
            FTool.add()
          })
        },
        Modal.Body(
          div(className := "row-fluid",
            InputInlineCp(useForm = useForm, label = "样本编号", name = "sampleId", labelWidth = 2, inputWidth = 8,
              value = sampleId, onChange = FTool.sampleIdChange, registerOptions = {
                val info = "样本编号"
                RegisterOptions(
                  required = ValidationValueMessage(value = true, message = s"${info}不能为空！"),
                  validate = FTool.sampleIdValidateF
                )
              }),
          )
        ),
        Modal.Footer(bsPrefix = "modal-footer bg-info")(
          button(`type` := "submit", className := "btn blue myAdd", "确定"),
          button(`type` := "button", className := "btn green", data - "dismiss" := "modal", "取消",
            onClick := FTool.handleClose),
        )
      )

    )

  }


}
